package com.sjtuy.galtxtreader.bookfile;

import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NormalBookSplitter implements BookSplitter {
    LinkedList<StringBuffer> chapters;
    Pattern chapterTitlePattern;
    DialogSplitter dialogSplitter;
    public NormalBookSplitter(String chapterTitleRegex){
        this.chapterTitlePattern=Pattern.compile(chapterTitleRegex);
        chapters = new LinkedList<>();
    }
    @Override
    public List<StringBuffer> split(String bookContent) {
        for(String paragraph:bookContent.split("\n")){
            paragraph=paragraph.trim();
            if(paragraph.length()==0)
                continue;
            if(isChapterTitle(paragraph)){
                chapters.addLast(new StringBuffer());
                chapters.getLast().append(paragraph).append("\n");
            }else if(!chapters.isEmpty()){
                if(dialogSplitter!=null){
                    chapters.getLast().append(dialogSplitter.split(paragraph));
                }else {
                    chapters.getLast().append("    ").append(paragraph).append("\n");
                }
            }
        }
        return chapters;
    }

    @Override
    public void setDialogSplitter(DialogSplitter dialogSplitter) {
        this.dialogSplitter=dialogSplitter;
    }

    private boolean isChapterTitle(String str){
        Matcher m = chapterTitlePattern.matcher(str);
        return m.find();
    }
}
